// Package middleware pkg/middleware/logger.go
package middleware

import (
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gozrd-admin-api/pkg/logger"
	"gozrd-admin-api/pkg/traceid"
)

// Logger 日志中间件
func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery

		// 从上下文中获取trace_id
		traceID, _ := c.Get(traceid.TraceIDKey)
		traceIDStr, ok := traceID.(string)
		if !ok {
			traceIDStr = ""
		}

		c.Next()

		end := time.Now()
		latency := end.Sub(start)

		// 记录日志
		logger.Info("请求日志",
			zap.String("trace_id", traceIDStr),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", c.ClientIP()),
			zap.Int("status", c.Writer.Status()),
			zap.String("latency", latency.String()),
			zap.String("user_agent", c.Request.UserAgent()),
		)
	}
}
